﻿using HY.Common;
using HY.Entity;
using HY.Service;
using HY.Web.Controllers;
using HY.Web.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HY.Web.Areas.Resource.Controllers
{
    public class LocationController : BaseController
    {
        LocationService service = new LocationService();
        // GET: Resource/Location
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult List(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var code = Request.Form["Code"];
                var where = $"L.IsDeleted=0";
                if (!string.IsNullOrWhiteSpace(code))
                    where += $" AND L.Code like '%{code}%'";
                var tuple = service.GetPageList<V_LocationList>("Location L JOIN Storehouse S ON L.StorehouseID=S.ID JOIN Park P ON L.ParkID=P.ID LEFT JOIN SysDept ON L.RentDeptID=SysDept.ID LEFT JOIN StoreType ST ON S.StoreTypeID=ST.ID", "L.ID,L.Code,L.Area,L.Height,L.Length,L.Width,L.IsRented,L.RentDeptID,L.CreateDate,S.ID StorehouseID,S.Code StorehouseCode,P.ID ParkID,P.Code ParkCode,SysDept.DeptName RentDeptName,P.ProvinceName,P.CityName,P.CountyName,ST.TypeName", where, page, limit, "L.CreateDate desc");
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "查询库位列表" }, ex);
            }
            return Json(returnModel);
        }

        public ActionResult Add()
        {
            ParkService parkService = new ParkService();
            StorehouseService storehouseService = new StorehouseService();
            ViewBag.ParkList = JsonConvert.SerializeObject(parkService.EFGetMany<Park>(p => !p.IsDeleted).Select(s => new { s.ID, s.Code }));
            ViewBag.StorehouseList = JsonConvert.SerializeObject(storehouseService.EFGetMany<Storehouse>(s => !s.IsDeleted).Select(s => new { s.ID, s.Code, s.ParkID }));
            return View();
        }
        [HttpPost]
        public JsonResult Add(Location model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Insert };
            try
            {
                model.CreateUserID = base.UserInfo.UserID;
                model.CreateDate = DateTime.Now;
                returnModel.count = service.Add(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"库位{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"库位{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        public ActionResult Edit(int? id)
        {
            ParkService parkService = new ParkService();
            StorehouseService storehouseService = new StorehouseService();
            ViewBag.ParkList = JsonConvert.SerializeObject(parkService.EFGetMany<Park>(p => !p.IsDeleted).Select(s => new { s.ID, s.Code }));
            ViewBag.StorehouseList = JsonConvert.SerializeObject(storehouseService.EFGetMany<Storehouse>(s => !s.IsDeleted).Select(s => new { s.ID, s.Code, s.ParkID }));
            var model = service.GetById<Location>(id);
            return View(model);
        }

        [HttpPost]
        public JsonResult Edit(Location model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Update };
            try
            {
                var oldModel = service.GetById<Location>(model.ID);
                model.IsDeleted = oldModel.IsDeleted;
                model.CreateDate = oldModel.CreateDate;
                model.CreateUserID = oldModel.CreateUserID;
                model.LastModifyUserID = base.UserInfo.UserID;
                model.LastModifyDate = DateTime.Now;
                returnModel.count = service.Update(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"库位{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"库位{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        public ActionResult ImageIndex(int id)
        {
            ViewBag.ID = id;
            return View();
        }

        public ActionResult ImageAdd(int id)
        {
            ViewBag.ID = id;
            return View();
        }

        [HttpPost]
        public JsonResult ImageUpload(int id)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Insert };
            try
            {
                var file = HttpContext.Request.Files.Count > 0 ? HttpContext.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0)
                {
                    string fileName = DateTime.Now.ToString("HHmmss") + Path.GetFileName(file.FileName);
                    string rootPath = Server.MapPath(Request.ApplicationPath);
                    string filePath = ConfigurationManager.AppSettings["LocationImagePath"] + "/" + DateTime.Now.ToString("yyyy-MM-dd");
                    DirectoryInfo dirInfo = Directory.CreateDirectory(rootPath + filePath);
                    file.SaveAs(Path.Combine(rootPath + filePath, fileName));

                    LocationImageService imageService = new LocationImageService();
                    LocationImage model = new LocationImage() { LocationID = id };
                    model.ImagePath = "/" + filePath + "/" + fileName;
                    model.ImageSize = file.ContentLength / 1024;//kb
                    model.CreateUserID = base.UserInfo.UserID;
                    model.CreateDate = DateTime.Now;
                    returnModel.count = imageService.Add(model);
                    returnModel.msg = "保存成功";
                    logInfo.LogMessage = $"库位图片{returnModel.msg}";
                    LogHelper.Info(logInfo);
                }
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"库位图片{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        [HttpPost]
        public JsonResult ImageShow(int id)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                LocationImageService imageService = new LocationImageService();
                IEnumerable<V_ImageData> v_ImageDatas = imageService.EFGetMany<LocationImage>(e => e.LocationID == id && !e.IsDeleted).Select(s => new V_ImageData { pid = s.ID, src = s.ImagePath });
                V_ImageShow v_ImageShow = new V_ImageShow();
                v_ImageShow.title = "";
                v_ImageShow.id = id;
                v_ImageShow.start = 0;
                v_ImageShow.data = v_ImageDatas;

                returnModel.count = v_ImageDatas.Count();
                returnModel.msg = returnModel.count > 0 ? "" : "未上传图片";
                returnModel.data = v_ImageShow;
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "获取失败";
                LogHelper.Error($"库位图片{returnModel.msg}", ex);
            }
            return Json(returnModel);
        }

        [HttpPost]
        [AllowAnonymous]
        public JsonResult SelectList(int storehouseID)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var list = service.EFGetMany<Location>(e => e.IsDeleted == false && e.StorehouseID == storehouseID).Select(s => new { value = s.ID, text = s.Code });
                returnModel = GetReturnModel(list.Count(), list);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error("获取库位下拉列表失败", ex);
            }
            return Json(returnModel);
        }
    }
}